<template>
  <n-modal v-model:show="isVisible" title="编辑品牌" preset="dialog" @close="onClose" style="height: 400px;width: 400px">
    <n-form @submit.prevent="handleSubmit" label-width="120px" class="form-container">
      <br>
      <div class="form-row" >
        <n-form-item label="产品品牌：" path="name" style="width: 250px">
          <n-input v-model:value="form.name" placeholder="请输入产品品牌"/>
        </n-form-item>
      </div>
      <div class="form-row">
        <n-form-item label="品牌简称：" path="color"  style="width: 250px">
          <n-input v-model:value="form.shortName" placeholder="请输入品牌简称"/>
        </n-form-item>
      </div>
      <br>
      <!-- 提交按钮 -->
      <div class="submit-row">
        <n-form-item>
          <n-button type="primary" native-type="submit" @click="handleSubmit">更新</n-button>
        </n-form-item>
      </div>
    </n-form>
  </n-modal>
</template>

<script setup>
import { ref, watch } from 'vue';
import { useUserStore } from "@/store/index.js";
import api from '@/api/admin.js';
import { List } from "echarts";

const userStore = useUserStore();
const id = userStore.getId();
const option = ref([]);

const emit = defineEmits(['updatePage']);
const props = defineProps({
  show1: {
    type: Boolean,
    required: true,
  },
  onClose: {
    type: Function,
    required: true,
  },
  brand: {
    type: Object,
    required: true,
  }
});

const isVisible = ref(props.show1);
watch(() => props.show1, (newVal) => {
  isVisible.value = newVal;
  if (newVal) {
    // 当对话框显示时，将传递过来的属性值填充到表单中
    form.value = { ...props.brand };
  }
});

const form = ref({
  name: '',
  shortName: '',

});

const handleSubmit = async () => {
  try {
    const res = await api.updateProductBrand(form.value);  // 调用更新接口
    if (res.code === 200) {
      emit("updatePage");
    } else {
      $message.error(res.message);
    }
  } catch (err) {
    $message.error("更新失败！");
  } finally {
    clear();
    props.onClose();
  }
};

const clear = () => {
  form.value = {
    name: '',
    shortName: '',
  };
};
</script>

<style scoped>
    .form-container {
        display: flex;
        flex-direction: column;
        width: 100%;
        position: relative;
    }

    .form-row {
        display: flex;
        align-items: center;
        width: 100%;
    }

    .form-row > n-form-item {
        flex: 1;
    }

    .submit-row {
        justify-content: center;
        display: flex;
        width: 100%;
    }
</style>
